#coding=utf-8
from keras.engine.saving import load_model
import cv2
import numpy as np

from load_dataset import resize_image, IMAGE_SIZE
from train_model import labels_name

MODEL_PATH = './model/model.h5'
traffic_sign_path = "././predict_traffic_sign/predict_traffic_sign .jpg"
# 加载模型
model = load_model(MODEL_PATH)
# 识别人脸
# 依然是根据后端系统确定维度顺序
cap = cv2.VideoCapture(0)

# 实时识别
while True:
    # 从摄像头读取图片
    success, img = cap.read()
    # img = cv2.flip(img, 1)
    img2=img.copy()
    img = cv2.rectangle(img, (212, 112), (468, 368), (0, 255, 0), 2)
    traffic_sign = img2[112:368,212:468]

    image = resize_image(traffic_sign, IMAGE_SIZE, IMAGE_SIZE)

    image = image.reshape((1, IMAGE_SIZE, IMAGE_SIZE, 3))

    # 浮点并归一化
    image = image.astype('float32')
    image /= 255.0

    # 给出输入属于各个类别的概率，我们是二值类别，则该函数会给出输入图像属于0和1的概率各为多少
    rst = model.predict(image)

    print(rst.argmax())

    # 给出类别预测
    result = model.predict_classes(image)
    cls = labels_name[int(result)]

    img = cv2.putText(img, cls, (212, 100), cv2.FONT_HERSHEY_SIMPLEX, 1, (0, 255, 0), 2)
    cv2.imshow('traffic_sign', img)   # imshow文件不能是中文，处理报错

    k = cv2.waitKey(1)
    if k == ord('q'):
        break

cap.release()
cv2.destroyAllWindows()

# 图片识别
# while True:
#     # 从摄像头读取图片
#     success, img = cap.read()
#     img = cv2.flip(img, 1)
#     img = cv2.rectangle(img, (276, 176), (404, 304), (0, 255, 0), 2)
#     traffic_sign = img[176:304, 276:404]
#
#     try:
#         cv2.imshow('image', img)   # imshow文件不能是中文，处理报错
#     except Exception as e:
#         pass
#
#     k = cv2.waitKey(1)
#     # if face != '':
#     #     cv2.imencode('.jpg', face)[1].tofile(face_path)
#     #     break
#
#     if k == ord(' '):
#         cv2.imencode('.jpg', traffic_sign)[1].tofile(traffic_sign_path)
#         break
#
# cap.release()
# cv2.destroyAllWindows()
#
# image = cv2.imdecode(np.fromfile(traffic_sign_path, dtype=np.int), cv2.IMREAD_COLOR)
# image = resize_image(image, IMAGE_SIZE, IMAGE_SIZE)
#
# image = image.reshape((1, IMAGE_SIZE, IMAGE_SIZE, 3))
#
# # 浮点并归一化
# image = image.astype('float32')
# image /= 255.0
#
# # 给出输入属于各个类别的概率，我们是二值类别，则该函数会给出输入图像属于0和1的概率各为多少
# rst = model.predict(image)
# print(rst)
#
# # 给出类别预测
# result = model.predict_classes(image)
#
# print(labels_name[int(result)])
